
const {MenuModel} = require('../../models/index')
const koaTool = require('../../commons/koa_tool')


class MenuController {

    //新增
    create = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['name', 'path', 'code', 'order','parent_code','disable'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        let newData = Object.assign({}, input, {
            
        })

        let detail = await MenuModel.create(newData)
        return koaTool.success(ctx,'创建成功');
    }

    //详情
    detail = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        const detail = await MenuModel.findById(input.id)
        if(detail){
            return koaTool.success(ctx,'获取成功',{
                detail
            });
        }
        return koaTool.error(ctx,'无该菜单信息');
    }
    //更新
    update = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let detail = await MenuModel.findById(input.id)
        if (!detail) {
            return koaTool.succ(ctx, {}, 405, '数据不存在')
        }
        const {
            name, path, order, disable
        } = input
        if (name) {
            detail.name = name
        }
        if(path){
            detail.path = path;
        }
        if (order) {
            detail.order = order
        }
        if (disable) {
            detail.disable = disable
        }
        await detail.save()
        return koaTool.success(ctx, '编辑成功');
    }
    //删除
    delete = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        await MenuModel.findByIdAndRemove(input.id)
        return koaTool.success(ctx, '删除成功');
    }
    //列表
    list = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        let query = {}
        let list = await MenuModel.find(query).sort([['order', 1]]);
        koaTool.succ(ctx, {
            list
        })
    }
    getValidList = async (ctx) => {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }

        let query = {
            'disable':1
        }
        let list = await MenuModel.find(query).sort([['order', 1]]);
        koaTool.succ(ctx, {
            list
        });
    }
}

module.exports=new MenuController()